﻿//-----------------------------------------------------------------------
// <copyright file="EnumHelper.cs" company="OverrideThis">
//     Copyright (c) 2010 OverrideThis.com
// </copyright>
//-----------------------------------------------------------------------
namespace OverrideThis.Core.Utilities
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Linq;
    using System.Reflection;

    public static class EnumHelper
    {
        /// <summary>
        /// Retrieve the description on the enum, e.g.
        /// [Description("Bright Pink")]
        /// BrightPink = 2,
        /// Then when you pass in the enum, it will retrieve the description
        /// </summary>
        /// <param name="en">The Enumeration</param>
        /// <returns>A string representing the friendly name</returns>
        public static string GetDescription(Enum en)
        {
            Type type = en.GetType();
            MemberInfo[] memInfo = type.GetMember(en.ToString());
            if (memInfo != null && memInfo.Length > 0)
            {
                object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);

                if (attrs != null && attrs.Length > 0)
                {
                    return ((DescriptionAttribute)attrs[0]).Description;
                }
            }
            return en.ToString();
        }


        /// <summary>
        /// Retrieves a KeyValuePair<string,string> Array that
        /// represents all values in an enum structure.
        /// </summary>
        /// <param name="type">
        /// The type of the enumeration.
        /// </param>
        /// <returns>
        /// An array of KeyValuePair&lt;string,string&gt;
        /// </returns>
        public static KeyValuePair<string, string>[] ToKeyValuePair(Type type)
        {
            return Enum.GetNames(type)
                .Select(m => new KeyValuePair<string, string>(m, GetDescription((Enum) Enum.Parse(type, m))))
                .ToArray();
        }

    }
}